﻿using System;
using System.Drawing.Imaging;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using CaptureImageTool;
using Rabbit.Modal;
using Rabbit.Utils;
using Rabbit.BusinessLogicLayer;
using System.Collections.Generic;
using System.Runtime.Remoting.Messaging;

namespace MicroBlogClient
{
    /// <summary>
    /// Interaction logic for UCPublishStatus.xaml
    /// </summary>
    public partial class UCPublishStatus : UserControl
    {
        Microsoft.Win32.OpenFileDialog openFileDialog = new Microsoft.Win32.OpenFileDialog();
        public UCPublishStatus()
        {
            InitializeComponent();
            LoadEmotions();
        }

        #region Event
        public static readonly RoutedEvent OnPublishStartEvent = EventManager.RegisterRoutedEvent("OnPublishStart",
             RoutingStrategy.Bubble, typeof(OneValueEventHandler<string>), typeof(UCPublishStatus));
        public event OneValueEventHandler<string> OnPublishStart
        {
            add { AddHandler(OnPublishStartEvent, value); }
            remove { RemoveHandler(OnPublishStartEvent, value); }
        }

        public static readonly RoutedEvent OnPublishFinishedEvent = EventManager.RegisterRoutedEvent("OnPublishFinished",
             RoutingStrategy.Bubble, typeof(OneValueEventHandler<Status>), typeof(UCPublishStatus));
        public event OneValueEventHandler<Status> OnPublishFinished
        {
            add { AddHandler(OnPublishFinishedEvent, value); }
            remove { RemoveHandler(OnPublishFinishedEvent, value); }
        }

        public static readonly RoutedEvent OnRequestingShowSuccessfulMessageEvent = EventManager.RegisterRoutedEvent("OnRequestingShowSuccessfulMessage",
             RoutingStrategy.Bubble, typeof(OneValueEventHandler<string>), typeof(UCPublishStatus));
        public event OneValueEventHandler<string> OnRequestingShowSuccessfulMessage
        {
            add { AddHandler(OnRequestingShowSuccessfulMessageEvent, value); }
            remove { RemoveHandler(OnRequestingShowSuccessfulMessageEvent, value); }
        }

        public static readonly RoutedEvent OnPublishFailedEvent = EventManager.RegisterRoutedEvent("OnPublishFailed",
             RoutingStrategy.Bubble, typeof(OneValueEventHandler<string>), typeof(UCPublishStatus));

        public event OneValueEventHandler<string> OnPublishFailed
        {
            add { AddHandler(OnPublishFailedEvent, value); }
            remove { RemoveHandler(OnPublishFailedEvent, value); }
        }

        private void RaiseStartingEvent(string message)
        {
            this.Dispatcher.BeginInvoke(new Action(() =>
            {
                OneValueEventArgs<string> args = new OneValueEventArgs<string>(OnPublishStartEvent);
                args.Value = message;
                RaiseEvent(args);
            }
            ));
        }

        private void RaiseFailedEvent(string message)
        {
            this.Dispatcher.BeginInvoke(new Action(() =>
            {
                btnPublish.SetCurrentValue(Button.IsEnabledProperty, true);
                OneValueEventArgs<string> args = new OneValueEventArgs<string>(OnPublishFailedEvent);
                args.Value = message;
                RaiseEvent(args);
            }
            ));
        }
        private void RaiseFinishedEvent(Status status)
        {
            this.Dispatcher.BeginInvoke(new Action(() =>
            {
                //clear rich text box's content and set button's status to be enabled
                rtbStatus.ClearContent();
                btnPublish.SetCurrentValue(Button.IsEnabledProperty, true);
                OneValueEventArgs<Status> args = new OneValueEventArgs<Status>(OnPublishFinishedEvent);
                args.Value = status;
                RaiseEvent(args);
            }
            ));
        }
        private void RaiseFinishedEvent(string message)
        {
            this.Dispatcher.BeginInvoke(new Action(() =>
            {
                OneValueEventArgs<string> args = new OneValueEventArgs<string>(OnRequestingShowSuccessfulMessageEvent);
                args.Value = message;
                RaiseEvent(args);
            }
            ));
        }
        
        #endregion
           
        private void btnPublishStatus_Click(object sender, RoutedEventArgs e)
        {
            if (rtbStatus.HasContent == false)
            {
                RaiseFailedEvent("说点什么再发表呀");
                return;
            }

            List<Image> imageList = rtbStatus.GetImages();
            string message = rtbStatus.Text;
            if (imageList.Count >1)
            {
                if (MessageBox.Show("微博内容中有" + imageList.Count + "个图片,但是只能为您发表第一张图片,确定返回修改么?","图片个数太多", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                {
                    return;
                }
            }
            RaiseStartingEvent("发表中...");
            btnPublish.SetCurrentValue(Button.IsEnabledProperty, false);
            Action publishDelegate= null;
            //no images, text status
            if (imageList.Count == 0)
            {
                publishDelegate = () =>
                {
                    try
                    {
                        Status status = StatusesBL.UpdateMyStatus(message);
                        if (status != null)
                        {
                            RaiseFinishedEvent(status);
                        }
                        else
                        {
                            RaiseFailedEvent("发表失败,请重试");
                        }
                    }
                    catch (SameStatusHasBeenPostedException)
                    {
                        RaiseFailedEvent("相同的微博内容不能发送两次");
                    }
                    catch (PublishAPICallTooFrequentException)
                    {
                        RaiseFailedEvent("您操作太频繁了，休息一下");
                    }
                    catch (Exception)
                    {
                        RaiseFailedEvent("发表失败,请重试");
                    }
                } ;
            }
            else
            {
                try
                {
                    BitmapImage bitmapImage = (imageList[0].Source as BitmapImage);
                    MemoryStream pictureStream = new MemoryStream();
                    BmpBitmapEncoder encoder = new BmpBitmapEncoder();
                    encoder.Frames.Add(BitmapFrame.Create((BitmapSource)bitmapImage));
                    encoder.Save(pictureStream);
                    pictureStream.Flush();
                    publishDelegate = () =>
                    {
                        try
                        {
                            message = string.IsNullOrEmpty(message.Trim()) ? "通过微兔版桌面微博分享图片" : message;
                            Status status = StatusesBL.UpdateMyStatusWithPicture(message, pictureStream);
                            if (status != null)
                            {
                                RaiseFinishedEvent(status);
                            }
                            else
                            {
                                RaiseFailedEvent("发表失败,请重试");
                            }
                        }
                        catch
                        {
                            RaiseFailedEvent("发表失败,请重试");
                        }
                    };
                }
                catch (Exception)
                {
                    RaiseFailedEvent("发表失败,请重试");
                }
            }
            publishDelegate.BeginInvoke(null, null); 
        }

       

        #region Emotions
        private void miEmotions_Click(object sender, RoutedEventArgs e)
        {
            popupEmotions.IsOpen = true;
        }

        private void LoadEmotions()
        {
            Properties.Settings settings = new Properties.Settings();
            var xEmotionClasses = settings.EmotionList;// Configurations.GetConfigElements("/Config/Emotions/Class");
            foreach (var emotionClass in xEmotionClasses)
            {
                TabItem tiEmotion = new TabItem();
                tiEmotion.Style = this.FindResource("emotionTabItemStyle") as Style;
                tiEmotion.Header = emotionClass.ClassName;
                tiEmotion.Height = 20;
                WrapPanel panel = new WrapPanel();
                panel.MinHeight = 100;
                var emotions = emotionClass.EmotionList;//.OrderBy((ele) => ele.Attribute("index"));
                foreach (var emotion in emotions)
                {
                    Border border = new Border();
                    border.Margin = new Thickness(2);
                    border.ToolTip = emotion.Name;
                    border.PreviewMouseLeftButtonUp += new MouseButtonEventHandler(border_PreviewMouseLeftButtonUp);
                    Style style = (Style)this.FindResource("emotionStyle");
                    border.Style = style;
                    Image image = new Image();
                    BitmapImage biImage = new BitmapImage();
                    biImage.BeginInit();
                    biImage.StreamSource = Application.GetResourceStream(new Uri(emotion.Path, UriKind.Relative)).Stream;
                    biImage.EndInit();
                    image.Source = biImage;
                    border.Child = image;
                    panel.Children.Add(border);
                }

                tiEmotion.Content = panel;
                tcEmotions.Items.Add(tiEmotion);
            }
        }

        void border_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            popupEmotions.IsOpen = false;
            rtbStatus.InsertText("[" + (sender as Border).ToolTip + "]");
        }
        #endregion

        #region Open picture select dialog
        private void miPicture_Click(object sender, RoutedEventArgs e)
        {
            openFileDialog.DefaultExt = "*.jpg";
            openFileDialog.Filter = "所有支持格式|*.jpg;*.jpeg;*.png;*.gif;*.bmp|jpg图片|*.jpg|jpeg图片|*.jpeg|png图片|*.png|gif图片|*.gif|bmp图片|*.bmp";
            bool? result = openFileDialog.ShowDialog();
            if (result == true)
            {
                rtbStatus.InsertImage(openFileDialog.FileName); 
            }
        }
        
        #endregion

        #region FeedBack
        private void miFeedback_Click(object sender, RoutedEventArgs e)
        {
            rtbStatus.InsertText(Application.Current.Resources["FeedBackAuthor"].ToString() + " ");
        }
        #endregion

        #region Topic
        private void miTopic_Click(object sender, RoutedEventArgs e)
        {
            string topicTips = "#输入话题标题#";
            rtbStatus.InsertText(topicTips);
        }
        #endregion

        #region Capture screen

        private void miCaptureScreen_Click(object sender, RoutedEventArgs e)
        {
            if (Keyboard.Modifiers == ModifierKeys.Control)
            {
                (App.Current.MainWindow as MainWindow).Hide();
                System.Threading.Thread.Sleep(30);
            }
            ShowCaptureScreen();
            App.Current.MainWindow.Show();
        }

        public void ShowCaptureScreen()
        {
            ImageCapture capture = new ImageCapture();

            if (capture.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                (App.Current.MainWindow as MainWindow).ShowAndActivate();
                MemoryStream stream = new MemoryStream();
                capture.Image.Save(stream, ImageFormat.Png);

                BitmapImage bitmap = new BitmapImage();
                bitmap.BeginInit();
                bitmap.DecodePixelWidth = 200;
                bitmap.StreamSource = stream;
                bitmap.EndInit();

                Image image = new Image();
                image.Source = bitmap;
                rtbStatus.InsertImage(image);
            }
        }
        #endregion

        private void miPaint_Click(object sender, RoutedEventArgs e)
        {

        }

        private void rtbStatus_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (!btnPublish.IsEnabled)
            {
                return;
            }

            if (e.Key == Key.Escape)
            {
                rtbStatus.ClearContent();
            }
            else if (e.KeyStates == Keyboard.GetKeyStates(Key.Enter)
               && Keyboard.Modifiers == ModifierKeys.Control
               )
            {
                //if Ctrl+Enter pressed,call btnPublishStatus_click to publish the status
                btnPublishStatus_Click(null, null);
            }
        }

        private void btnClearStatus_Click(object sender, RoutedEventArgs e)
        {
            rtbStatus.ClearContent(); 
        }

        private void miAddAuthorAsFriend_Click(object sender, RoutedEventArgs e)
        {
            RaiseStartingEvent("正在关注作者");
            long userID = long.Parse(App.Current.Resources["AuthorId"].ToString());
            Action makeFriends = () =>
            {
                User result = UserBL.CreateFriendship(userID);
                if (result == null)
                {
                    RaiseFinishedEvent("您已经关注过作者");
                }
                else
                {
                    RaiseFinishedEvent("关注作者成功");
                }
            };
            makeFriends.BeginInvoke(null, null);
        }
    }
}
